package com.hwadee.property.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hwadee.property.mapper.ComplainMapper;
import com.hwadee.property.pojo.Complain;
import com.hwadee.property.service.IComplainService;
import com.hwadee.property.dto.PageResult;
import com.hwadee.property.util.DateUtil;
import com.hwadee.property.util.ErrorCodes;
import com.hwadee.property.util.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class ComplainServiceImpl extends ServiceImpl<ComplainMapper, Complain> implements IComplainService {

    @Autowired
    private ComplainMapper complainMapper;

    @Override
    public PageResult<Complain> getComplainListPage(int current, int size, Long communityId, Long ownerId, String status) {
/*        // 校验参数合法性
        if (communityId == null || communityId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID无效");
        }
        if (ownerId != null && ownerId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "业主ID无效");
        }
        if (status != null && !isValidStatus(status)) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "状态不合法");
        }*/

        // 确保 current 至少为 1
        current = Math.max(current, 1);
        size = Math.max(size, 1);

        // 查询总记录数
        int total = complainMapper.countComplains(communityId, ownerId, status);

        // 只有当 total > 0 时才查询数据，防止不必要的 SQL 查询
        List<Complain> records = (total > 0) ? complainMapper.getComplains(communityId, ownerId, status, size, (current - 1) * size) : Collections.emptyList();

        // 返回封装的分页结果
        return new PageResult<>(total, current, size, records);
    }

    @Override
    public boolean addComplain(Complain complain) {
        // 校验合法性
        if (complain == null || complain.getCommunityId() == null || complain.getCommunityId() <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID无效");
        }

        // 设置默认值
        complain.setProcessingStatus("待处理");
        complain.setComplainDate(DateUtil.dateToString(new Date()));
        return save(complain);
    }

    @Override
    public boolean updateStatus(Long id, String status, Long handlerId, String completionDate) throws ParseException {
        // 校验合法性
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "投诉ID无效");
        }

        // 查找投诉信息
        Complain complain = getById(id);
        if (complain == null) {
            throw new BusinessException(ErrorCodes.NOT_FOUND, "投诉记录未找到");
        }

        // 检查 processingStatus 是否合法
        if (!isValidStatus(status)) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "处理状态不合法，必须为：待处理、处理中、已完成、已取消");
        }

        complain.setProcessingStatus(status);
        complain.setHandlerId(handlerId);
        complain.setCompletionDate(completionDate);
        return updateById(complain);
    }

    @Override
    public long getUnprocessedComplainCount(Long communityId) {
        // 校验合法性
        if (communityId == null || communityId <= 0) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "小区ID无效");
        }

        QueryWrapper<Complain> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("community_id", communityId);
        queryWrapper.eq("processing_status", "待处理");
        return count(queryWrapper);
    }

    @Override
    public List<Complain> listByOwnerId(Long userId) {
        // 校验业主ID
        if (userId == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "业主ID不能为空");
        }
        return this.list(new LambdaQueryWrapper<Complain>().eq(Complain::getOwnerId, userId));
    }

    @Override
    public List<Complain> listByCommunityId(Long communityId) {
        // 校验小区ID
        if (communityId == null) {
            throw new BusinessException(ErrorCodes.INVALID_PARAMETER, "业主ID不能为空");
        }
        return this.list(new LambdaQueryWrapper<Complain>().eq(Complain::getCommunityId, communityId));
    }

    /**
     * 验证处理状态是否合法
     * @param status 需要验证的状态
     * @return 如果合法返回 true，否则返回 false
     */
    private boolean isValidStatus(String status) {
        return "待处理".equals(status) || "处理中".equals(status) || "已完成".equals(status) || "已取消".equals(status);
    }
}
